/*
 * ServerMonkey.cpp
 *
 *  Created on: Jun 20, 2013
 *      Author: Dan
 */

#include "ServerMonkey.h"

int main(int argc, char* argv[]) {

	sm::ServerMonkey* server = NULL;

	if (argc > 1) {
		try {
			server = new sm::ServerMonkey(argv[1]);
		} catch (std::exception&) {
			Log::error("Error reading config file.");
		}
	} else {
		Log::error("No configuration file selected.");
	}
	if (server) {
		server->run();
		delete server;
	}

	return 1;
}

namespace sm {

ServerMonkey::ServerMonkey(char* aFile) throw (monkeyXML::parseException) {
	std::ifstream xmlfile(aFile);
	if (xmlfile) {
		try {
			monkeyXML::XMLHeader h(xmlfile);
			monkeyXML::XMLTree t(xmlfile);
			theConfigs = new Config(t);

			Log::setDebugMode(theConfigs->isDebugModeOn());
			Log::setFile(theConfigs->getTheLogFile());

			theInputDir = NULL;
			theInputDir = new InputDir(theConfigs->getTheInputDir());

			thePTF = NULL;
			thePTF = new PlayerTableFile(theConfigs->getThePlayerFile());

		} catch (monkeyXML::parseException&) {
			Log::error("Error reading the header");
			monkeyXML::parseException e;
			throw e;
		}
	} else {
		Log::error("Error opening the file");
		monkeyXML::parseException e;
		throw e;
	}
}

int ServerMonkey::run() {
	sm::Reciept* reciept;
	std::string incoming = theInputDir->getFileName();
	if (incoming != "") {
		std::ifstream xmlfile(incoming.c_str());
		monkeyXML::XMLHeader h(xmlfile);
		monkeyXML::XMLTree t(xmlfile);
		if (t.getTag().find("AccountMsg") != t.getTag().npos) {
			Log::event("Recieved an Account Msg");
			reciept = thePTF->createreceipt(t);
			reciept->writeToStream(std::cout);
			delete reciept;
		}
	}
	return 0;
}

ServerMonkey::~ServerMonkey() {
	if (theConfigs) {
		delete theConfigs;
	}
	if (theInputDir) {
		delete theInputDir;
	}
	if (thePTF) {
		delete thePTF;
	}
}

}
